package com.hanliy.storage.impl;

import com.hanliy.storage.StorageType;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.Data;

import java.io.InputStream;

/**
 * @author hanyulin
 * @apiNote
 * @date 2021/12/4 11:01
 */
@Data
public class QiniuStorageImpl implements StorageType {

    private String endpoint;
    private String accessKey;
    private String secretKey;
    private String bucketName;

    private Auth auth;
    private UploadManager uploadManager;
    private BucketManager bucketManager;

    @Override
    public void store(InputStream inputStream, long contentLength, String contentType, String keyName) {
        if (uploadManager == null) {
            if (auth == null) {
                auth = Auth.create(accessKey, secretKey);
            }
            uploadManager = new UploadManager(new Configuration());
        }
        try {
            String upToken = auth.uploadToken(bucketName);
            uploadManager.put(inputStream, keyName, upToken, null, contentType);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String generateUrl(String keyName) {
        return endpoint + "/" + keyName;
    }

    @Override
    public void delete(String key) {
        if (bucketManager == null) {
            if (auth == null) {
                auth = Auth.create(accessKey, secretKey);
            }
            bucketManager = new BucketManager(auth, new Configuration());
        }
        try {
            bucketManager.delete(bucketName, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
